<template>
  <div class="category-details">
    <div class="content">
      <!-- 搜索区域 -->
      <div class="query">
        <nut-input v-model="queryGame" :placeholder="t('inside_page_search_placeholder')" clearable
          @update:model-value="onClickSearch">
          <template #left>
            <iconpark-icon icon-id="sousuo" size=".8rem" class="refresh"></iconpark-icon>
          </template>
        </nut-input>
        <ImgT :src="`/imgs/home/close.webp`" class="close_img" alt="" @click="showLeft = false" />
      </div>

      <div class="main_content">
        <!-- 左侧tab  -->
        <div class="tab" id="tab_target">
          <div class="tab_wrap">
            <div v-for="(v, i) in gameTabs" :key="i">
              <div class="tab_item" :class="{ tab_ac: tabDta && tabDta.id == v.id }" @click="onClickTab(v, $event)">
                <ImgT :src="`${settings.backend_upload}${v.icon_h5}`" class="tab_style" alt="" />
                <span>{{ v.name[lang] }}</span>
              </div>
              <div class="show_second_list" v-if="
                threeGameKinds.length > 0 && tabDta?.name == v.name && state.type == 1
              ">
                <iconpark-icon icon-id="xia" color="#fff" size="0.8rem"></iconpark-icon>
              </div>

              <!-- 次级菜单 -->
              <div v-if="
                threeGameKinds.length > 0 && tabDta?.name == v.name && state.type == 1
              " class="second_tab">
                <div v-for="item in threeGameKinds" :class="{ tab_ac: state.agentId == item.id }" :key="item.id"
                  class="second_tab_item" @click="onClickSTab(item)">
                  <img :src="settings.backend_upload + item.picture_pc" />
                  <span>{{ item.name[lang] }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 右侧数据 -->
        <div class="games_box" v-if="state.type == 1">
          <!-- {{ state.kindList }} -->
          <nut-tabs v-model="state.lableActive" title-scroll @change="changeLableTab">
            <nut-tab-pane :title="unserialize(item.kind_name, true)" :pane-key="item.kindId"
              v-for="(item, i) in state.kindList" :key="i">
              <div :style="gameBoxStyle()">
                <nut-infinite-loading v-model="infinityValue" :has-more="hasMore" @load-more="onLoad" :threshold="500">
                  <nut-pull-refresh v-model="refreshing" @refresh="pulldown">
                    <nut-empty v-if="!loading && !state.list.length" :description="t('nomore_data')"></nut-empty>
                    <div class="game_list" v-if="state.list">
                      <div class="item" v-for="(v, i) in state.list" :key="i">
                        <GameItem :item="v"></GameItem>
                      </div>
                    </div>
                  </nut-pull-refresh>
                </nut-infinite-loading>
              </div>
            </nut-tab-pane>
          </nut-tabs>
        </div>
        <!-- 体育 视讯没有  二级菜单 -->
        <div class="games_box games_box2" v-if="state.type == 2">
          <nut-empty v-if="threeGameKinds.length == 0" :description="t('nomore_data')"></nut-empty>
          <div class="game_list game_list1" v-else :style="gameBoxStyle1()">
            <div class="item_2" v-for="(v, i) in threeGameKinds" :key="i" @click.stop="onPlayGame(v)">
              <div class="item_bg">
                <div>
                  <img :src="settings.backend_upload + v.logo_h5" class="logo_h5" />
                  <span>{{ unserialize(v.name, false) }}</span>
                </div>
                <img :src="settings.backend_upload + v.picture_h5" />
              </div>

              <!-- <div class="cover cover1">
                                <img :src="settings.backend_upload + v.picture_h5" />
                                <iconpark-icon v-if="hasLogin" class="fav"
                                    :name="allCollected.includes(v.id) ? 'shoucang-sel' : 'shoucang-def'" size="1rem"
                                    @click.stop="reqCollect(v, allCollected)"></iconpark-icon>
                            </div>
                            <div class="title title1">{{ unserialize(v.name, false) }}</div> -->
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
// import { useRouter } from 'vue-router';
import {
  onBeforeMount,
  onMounted,
  onUnmounted,
  reactive,
  ref,
  watch,
  nextTick,
} from "vue";

import { storeToRefs } from "pinia";
import { Page } from "@/store/page";
import pinia from "@/store";
import { NetPacket } from "@/netBase/NetPacket";
import H5Websocket from "@/net/Net1";
import { NetMsgType } from "@/netBase/NetMsgType";
import { MessageEvent2 } from "@/net/MessageEvent2";
import { useI18n } from "vue-i18n";
import { Local } from "@/utils/storage";
// import { showToast } from '@nutui/nutui';
import { User } from "@/store/user";
import { unserialize, onPlayGame } from "@/utils/useStoreMethods";
import GameItem from "@/components/GameItem.vue";
const { appHeight, allCollected } = storeToRefs(User(pinia));
// const router = useRouter()
// const route = useRoute()
// const isLoading = ref(false)
// const hasVideoImgList = ["BG", "DG", "EVO", "SEXY", "MG", "SA", "IM", "SABA", "CMD368"];

const { settings, lang, homeGameData, showLeft } = storeToRefs(Page(pinia));

const { t } = useI18n();

const queryGame = ref("");

// 加载更多
const loading = ref(false);
const refreshing = ref(false);
// 游戏平台id  -1为查看全部的游戏

// 右侧标签id  是否属于场馆或者火热的游戏 为0时 则kindId 为场馆id或火热  为1时  则kindId取右侧tab的值

// 表示场馆id // -1为查找当前平台所有的游戏

// 右侧标签点击样式

const state = reactive({
  // 游戏平台id  -1为查看全部的游戏
  agentId: -1,

  // 自定义标签 -1为全部  -2为收藏，-3为最近
  lableId: 0,

  // //也表示场馆id
  kindId: 1,

  // 右上方侧标签点击样式
  lableActive: -1,

  // 所有标签集合
  kindList: [] as any,

  // 当前点击的游戏
  currentGame: null as any,

  // 游戏集合
  list: [] as any,
  // 游戏输入框节流
  timer: null as any,
  // 游戏类型
  type: 1,
});
const params: any = reactive({
  // 参数
  isLoad: false,
  isEnd: false,
  pageSize: 30,
  page: 1,
});
const first = {
  kind_name: '{"zh-CN":"全部","vi-VN":"tất cả","en-US":"All"}',
  kindId: 0,
  key: 0,
  icon_after: "/img/game/all_un.webp",
  icon_before: "/img/game/all.webp",
};
const first_hot = {
  kind_name: '{"zh-CN":"热门","vi-VN":"Phổ biến","en-US":"Popular"}',
  kindId: 0,
  key: 0,
  icon_after: "/img/game/all_un.webp",
  icon_before: "/img/game/all.webp",
};
const last = [
  {
    kind_name: '{"zh-CN":"最近","vi-VN":"gần đây","en-US":"Recent"}',
    kindId: -3,
    key: 2,
    icon_after: "/img/game/zuijin_un.webp",
    icon_before: "/img/game/zuijin.webp",
  },
  {
    kind_name: '{"zh-CN":"收藏","vi-VN":"Yêu thích","en-US":"Favorites"}',
    kindId: -2,
    key: 3,
    icon_after: "/img/game/shoucang_un.webp",
    icon_before: "/img/game/shoucang.webp",
  },
];

let gameName = ref("");

// let favoriteData = ref<any[]>([])
// let resultList: any = reactive([])
const tabDta = ref();
// let platformId = ref<any>(0)
// let venueId = ref<any>(0)
let gameTabs: any = reactive([]);

// let second_game_Tabs = ref<any[]>([])
// let currentGameData: any = ref([])  // 当前筛选的数据

let threeGameKinds = ref<any[]>([]);
// const imgPrefix = 'http://18.162.112.52:8033/uploads/'
// const TabType = {
//     FAVORITE: 88
// }
const gameBoxStyle = () => {
  return { height: `calc(${appHeight.value}px - 54vw - 11.73333vw)` };
};
const gameBoxStyle1 = () => {
  return { height: `calc(${appHeight.value}px - 54vw)` };
};
const getHomeData = () => {
  const data = homeGameData.value.find((e: any) => e.id == Number(state.kindId));
  gameTabs = homeGameData.value.filter((e: any) => e.id > 0);
  gameTabs.forEach((item: any, index: number) => {
    item.flag = index + 1;
  });
  gameName.value = unserialize(data.name, false); // name as string
};

const handlePlatformKind = (res: any) => {
  if (res.label.length > 0) {
    state.kindList = [first, ...last];
    console.log();
  } else {
    state.kindList = [first, ...last];
  }
};

// 返回游戏列表
const hasMore = ref(true);
const infinityValue = ref(false);
const handleGames = (res: any) => {
  state.list.push(...res.info);
  loading.value = false;
  if (res.info.length < params.pageSize) {
    hasMore.value = false;
  }
  if (res.info.length == 0) {
    hasMore.value = true;
  }
  infinityValue.value = false;
  MessageEvent2.removeMsgEvent(NetMsgType.msgType.msg_notify_get_games_in_platform, null);
};

const handleQuery = (res: any) => {
  state.list = res.info;
};

//切换上方标签事件
const changeLableTab = (item: any) => {
  hasMore.value = true;
  state.lableId = Number(item.paneKey);
  state.lableActive = Number(item.paneKey);
  resetData();
  queryData();
};

const onClickSearch = () => {
  if (queryGame.value) {
    if (state.timer != null) {
      clearTimeout(state.timer);
    }
    state.timer = setTimeout(() => {
      let tb = NetPacket.req_look_for_game_name();
      tb.agentId = state.agentId;
      tb.kindId = state.kindId;
      tb.name = queryGame.value;
      H5Websocket.sendMessageHandler(tb);
    }, 500);
  }
};

// 点击tab
const onClickTab = (v: any, el: any) => {
  // 体育没有次级菜单
  if (![3, 4].includes(v.id)) {
    state.type = 1;
    setTimeout(() => {
      if (el) {
        const tab_target: any = document.getElementById("tab_target");
        tab_target.scrollTo(0, el.target.offsetTop - 108);
      }
    }, 100);
  } else {
    state.type = 2;
  }

  if (tabDta.value?.id == v.id && threeGameKinds.value.length && ![3, 4].includes(v.id)) {
    threeGameKinds.value = [];
  } else {
    threeGameKinds.value = v.three_platform;
    console.log("threeGameKinds", threeGameKinds.value);
  }
  hasMore.value = true;
  state.lableActive = 0;
  state.lableId = 0;
  tabDta.value = v;
  state.agentId = -1;
  state.kindId = v.id;
  resetData();
  getInitData(state.agentId);
  queryData();
};

// 点击厂商切换游戏
const onClickSTab = (v: any) => {
  state.agentId = v.id;
  state.kindList = [];
  hasMore.value = true;
  resetData();
  getInitData(state.agentId);
  queryData();
};

const getInitData = (agentId: any) => {
  if (agentId != -1) {
    const req = NetPacket.req_get_kind_in_platform();
    req.agentId = agentId;
    req.kindId = state.kindId;
    req.pageSize = 10;
    H5Websocket.sendMessageHandler(req);
  } else {
    state.kindList = [first_hot, ...last];
  }
};

const resetData = async () => {
  loading.value = false;
  params.page = 1;
  params.pageSize = 30;
  queryGame.value = ''
  state.list = [];
  await queryData();
  refreshing.value = false;
};

const onLoad = async () => {
  if (params.isEnd) return;
  params.isLoad = true;
  params.page++;
  queryData();
};

const pulldown = () => {
  resetData();
  getInitData(state.agentId);
};

// 查询游戏数据
const queryData = () => {
  // 查询
  MessageEvent2.addMsgEvent(
    NetMsgType.msgType.msg_notify_get_games_in_platform,
    handleGames
  );
  loading.value = true;
  const query = NetPacket.req_get_games_in_platform();
  query.agentId = state.agentId;
  query.kindId = state.kindId;
  query.lableId = state.lableId;
  query.page = params.page;
  query.pageSize = params.pageSize;
  H5Websocket.sendMessageHandler(query);
};

// 打开侧滑页面
watch(
  showLeft,
  (n: boolean) => {
    if (n) {
      params.page = 1;
      params.pageSize = 30;
      nextTick(() => {
        onClickTab(gameTabs[0], "");
        queryData();
      });
      MessageEvent2.addMsgEvent(
        NetMsgType.msgType.msg_notify_get_kind_in_platform,
        handlePlatformKind
      );
      MessageEvent2.addMsgEvent(
        NetMsgType.msgType.msg_notify_look_for_game_name,
        handleQuery
      );
    } else {
      MessageEvent2.removeMsgEvent(
        NetMsgType.msgType.msg_notify_get_kind_in_platform,
        null
      );
      // MessageEvent2.removeMsgEvent(NetMsgType.msgType.msg_notify_get_games_in_platform, null);
      MessageEvent2.removeMsgEvent(
        NetMsgType.msgType.msg_notify_look_for_game_name,
        null
      );
    }
  },
  { immediate: true }
);

watch(allCollected, (val) => {
  if (state.lableActive == -2) {
    let gameId = Local.get("gameId");
    const isCollect = val.includes(gameId);
    if (!isCollect) {
      state.list = state.list.filter((item: any) => item.id != gameId);
    }
  }
});

onBeforeMount(() => {
  getHomeData();
});
onMounted(() => {
  // getFavs()
});
onUnmounted(() => { });
</script>

<style scoped lang="scss">
.category-details {
  background-image: url(/imgs/common/bg_img.webp);
  background-size: 100% 100%;
  background-color: #000000;
  display: grid;
  grid-template-rows: auto 1fr;
  height: 100%;
  overflow: hidden;

  .close_img {
    width: 32px;
    height: 32px;
    margin-left: 8px;
  }

  :deep(.nut-tabs .nut-tabs__titles) {
    padding: 0;
    height: 44px;
  }

  .amount_box {
    display: flex;
    align-items: center;

    >span {
      margin: 0 6px;
    }
  }

  .content {
    width: 100%;
    padding: 0 10px;
    margin-top: 14px;
  }

  .main_content {
    display: flex;

    // height: calc(100vh - 240px);
    // overflow-y: scroll;
    >.games_box {
      width: 276px;
      padding-left: 12px;
    }

    .games_box2 {
      padding-left: unset;
    }
  }

  .tab {
    background-size: 100% 100%;
    padding: 0 4px;
    width: 80px;
    font-size: 12px;
    height: calc(100vh - 240px);
    overflow-y: scroll;

    .tab_wrap {
      display: flex;
      flex-direction: column;
      gap: 8px;
    }

    // div {
    //     position: relative;
    // }

    .tab_item {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      gap: 6px;
      color: #c6c4f5;
      width: 72px;
      height: 54px;
      font-size: 14px;
      border-radius: 8px;
      background-color: #131232;
      box-shadow: 0.5px 0.5px 1px 0px #2e296b inset;

      >img {
        width: 20px;
        height: 20px;
        // height: 100%;
      }
    }

    .show_second_list {
      // right: -28px;
      width: 16px;
      height: 16px;
      background: #131232;
      border-radius: 50%;
      display: flex;
      justify-content: center;
      align-items: center;
      rotate: 180deg;
      margin-top: -30px;
      margin-left: 65px;

      // position: absolute;
      // top: -10px;

      //po // transform: translate(-30px)
      // margin-top: -40px;
    }

    .tab_ac {
      color: #fff !important;
      background: linear-gradient(180deg, #5567ff 0%, #9e1eff 100%) !important;
      box-shadow: 0.5px 0.5px 1px 0px #9b9eff inset !important;
    }

    .second_tab {
      margin-top: 20px;
    }

    .second_tab_item {
      height: 42px;
      border-radius: 8px;
      background: #282747;
      color: #c6c4f5;
      font-size: 12px;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-top: 8px;
      display: flex;
      flex-direction: column;

      img {
        height: 28px;
      }
    }
  }

  .query {
    margin: 10px 0;
    display: flex;
    justify-content: space-between;
    align-items: center;

    :deep(.nut-input--border) {
      border-bottom: none;
    }

    // :deep(.nut-input-left-box){
    //   margin-right: ;
    // }
    &:deep(.nut-input) {
      height: 36px;
      padding: 8px;
      border-radius: 8px;
      background: #1d1c3c;

      input {
        &::placeholder {
          color: #504f6f;
        }
      }
    }
  }

  .scroll-view {
    height: 74vh;
    overflow: auto;
  }

  .game_list1 {
    gap: 8px;
  }

  .game_list {
    display: flex;
    flex-wrap: wrap;
    overflow-y: auto;

    .item_2 {
      img {
        width: 255px;
        height: 104px;
      }

      .item_bg {
        display: flex;
        background: url(/imgs/category/video.webp) no-repeat;
        background-size: 100% 100%;
        width: 255px;
        height: 104px;
        margin-left: 10px;

        div {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;

          span {
            color: #b5b4bb;
            font-size: 14px;
            font-weight: 600;
          }
        }

        .logo_h5 {
          width: 92px;
          height: 45px;
        }
      }
    }

    .item {
      width: 82px;
      height: 108px;
      margin-right: 8px;
      margin-bottom: 8px;
      border-radius: 8px;
      background: #1a1944;
      position: relative;
    }

    .item1 {
      width: 112px;
      height: 148px;
    }

    :nth-child(3n) {
      margin-right: 0;
    }

    .cover1 {
      width: 112px;
      height: 112px;
    }

    .title {
      width: 90%;
      margin: 0 auto;
      text-align: center;
      font-size: 14px;
      color: #fff;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .title1 {
      height: 36px;
      line-height: 36px;
    }
  }
}

.games_box_other {
  flex: 1;

  .games_box_other_item {
    border-radius: 8px;
    overflow: hidden;
    margin-bottom: 8px;

    img {
      height: 94px;
      width: 100%;
    }
  }
}
</style>
